package com.yln.watcher.client;

import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class MasterContext implements ZkContext {
    // 当前所有的workers 例：["worker-1", "worker-2"]
    private List<String> workerList = new ArrayList<>();

    // 当前还未分配的task
    private List<String> taskList = new ArrayList<>();

    public List<String> getAllWorkerList() {
        return workerList;
    }

    @Override
    public void cacheWorkers(List<String> allWorkers) {
        this.workerList = allWorkers;
    }

    @Override
    public void cacheTasks(List<String> tasks) {
        this.taskList = tasks;
    }

    @Override
    public List<String> getHasProceededTasks() {
        throw new RuntimeException("Master node not support get proceeded tasks.");
    }

    @Override
    public void taskProcessing(String task) {

    }

    @Override
    public void addNotAssignedTasks(List<String> taskNodes) {
        taskList.addAll(taskNodes);
    }

    @Override
    public Optional<String> randomWorker() {
        log.info("worker list cache: {}", workerList);
        int size = workerList.size();
        if (size == 0) {
            // 当前没有任何workers注册进来
            return Optional.empty();
        }
        int index = new Random().nextInt(size);
        log.info("get worker from worker list cache. index: {}", index);
        return Optional.of(workerList.get(index));
    }

    @Override
    public List<String> getAllWorkers() {
        return workerList;
    }

    @Override
    public List<String> getAllTasks() {
        return taskList;
    }

    @Override
    public void removeTask(String task) {
        taskList.remove(task);
    }
}
